import datetime
from base import log, mysqlConnect, tangtemp
import time


def insert(inputdate, fromtime, totime, member_id):
    logging = log.init(1)
    db, cursor = mysqlConnect.connect("sit", "kaikela_stat")
    sheet_name = "s_learn_time_heartbeat_log"
    logging.info("=================================================")
    sub_minutes = tangtemp.dateToMinutes(fromtime, totime)
    datestring = inputdate + " " + ":".join(fromtime.split("-")) + ":00"
    fromtimedatetime = datetime.datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S")
    fromtimedate = inputdate
    for i in range(0, sub_minutes + 1):
        # send_msg_time = "send_msg_time"
        create_date = "create_date"
        # learn_start = 0
        # learn_end = 0
        heartbeat_type = 1
        heartbeat_stimestamp_datetime = fromtimedatetime + datetime.timedelta(minutes=i)
        heartbeat_timestamp = int(time.mktime(heartbeat_stimestamp_datetime.timetuple()))
        heartbeat_date = fromtimedate
        # if i == 0:
        #     learn_start = 1
        # elif i == sub_minutes:
        #     learn_end = 1
        lastvalues = [member_id, str(heartbeat_date), str(heartbeat_timestamp), str(heartbeat_type),
                      str(create_date)]
        values = []
        for value in lastvalues:
            if value is create_date:
                newvalue = "NOW()"
            else:
                newvalue = "\'" + value + "\'"
            values.append(newvalue)
        sql = ""
        sql = sql + "INSERT INTO "
        sql = sql + sheet_name
        sql = sql + " (`member_id`, `heartbeat_date`, `heartbeat_timestamp`, `heartbeat_type`," \
                    " `create_date`)"
        sql = sql + " VALUES ("
        sql = sql + ",".join(values)
        sql = sql + ")"
        sql.replace('""', "NULL")
        logging.info("==========================开始执行SQL==========================")
        logging.info(sql)
        try:
            cursor.execute(sql)
            db.commit()
        except Exception as e:
            logging.info("==========================SQL执行失败==========================")
            logging.error(e)
            print(e)
